//fd265d
import React, {Component} from 'react';
import {Image,TouchableOpacity,StyleSheet,View,Animated} from 'react-native';
import {scaleSize} from '../../utils/screen';
import FontText from './FontText';
import PropTypes from 'prop-types';

export default class Switch extends Component {
    constructor(props){
        super(props);
        let {height = scaleSize(30),width = scaleSize(80)} = props;
        let left = 0;
        if(props.checked){
            left = width - height;
        }
        this.state = {
            left:new Animated.Value(left),
            checked:props.checked
        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.checked !== nextProps.checked) {
          const { checked, height = scaleSize(30), width = scaleSize(80) } = nextProps;
          const left = checked ? (width - height) : 0;
          this.setState({
            left: new Animated.Value(left),
            checked,
          });
        }
    }

    render() {
        let {height = scaleSize(30),text = "",width = scaleSize(80),children,activeColor = "#fd265d",defaultColor = "#394158"} = this.props;
        let {checked,left} = this.state;
        let color = checked?activeColor:defaultColor;
        let toggleStyles = {height:height,borderRadius:height,width:width,backgroundColor: color};
        return (
            <TouchableOpacity 
                activeOpacity = {1}
                onPress = {()=>this.onPress()}
                style = {styles.box}>
                <View
                    style={[styles.toggle, toggleStyles]}
                    >
                    <Animated.View style = {[styles.bar,{height:height,width:height ,borderRadius: height,borderColor:color},{transform:[{translateX:left}]}]}></Animated.View>
                </View>
                {children}
            </TouchableOpacity>
        );
    }
    onPress(){
        let {onPress,width = scaleSize(80),height = scaleSize(30)} = this.props;
        let nchecked = !this.state.checked;
        let left = 0;
        if(nchecked){
            left = width - height;
        }
        Animated.timing(this.state.left, {
            toValue: left,
            duration:100,
            useNativeDriver: true,
        }).start(()=>{
            this.setState({
                checked:nchecked
            },()=>{
                onPress && onPress(nchecked);
            })
        });
    }
}

const styles = StyleSheet.create({
    box:{
        height:scaleSize(80),
        flexDirection: 'row',
        alignItems: 'center',
    },
    bar:{
        backgroundColor: "#fff",
        paddingRight: scaleSize(9),
        position: "absolute",
        top:-1,
        left:-1,
        borderWidth:1
    },
    toggle: {
        borderWidth: 1,
        borderColor: "#ffffff",
    },
})